<template>
  <div class="card-containers">
    <div class="containers">
      <div class="cards">
        <div class="headers clearfix">
          <span>中药材分类</span>
          <el-button @click="toggleAddForm" type="primary">打开/关闭</el-button>
        </div>
        <div class="content">
          <div v-for="item in toggleInit" :key="item.category" class="list-item">
            <el-checkbox @change="selectTcItem(item.id)">
              <span>{{ item.category }}</span>
            </el-checkbox>
          </div>
        </div>
        <div v-show="showAddForm" class="form-container">
          <el-row :gutter="15">
            <el-form ref="elForm" :model="formData"  status-icon :rules="rules" size="medium" label-width="100px">
              <el-col :span="24">
                <el-form-item label="" prop="category">
                  <el-input v-model="formData.category" type="textarea" placeholder="分类设置" clearable :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item size="large">
                  <el-button type="primary" @click="submitForm">提交</el-button>
                  <el-button @click="deleteSelectedItems">删除</el-button>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </div>
      </div>
    </div>
    <div class="containers">
      <div class="cards">
        <div class="headers clearfix">
          <span>西药分类</span>
          <el-button @click="toggleAddForm2" type="primary">打开/关闭</el-button>
        </div>
        <div class="content">
          <div v-for="item in toggleInit2" :key="item.category" class="list-item">
            <el-checkbox @change="selectVmItem(item.id)">
              <span>{{ item.category }}</span>
            </el-checkbox>
          </div>
        </div>
        <div v-show="showAddForm2" class="form-container">
          <el-row :gutter="15">
            <el-form ref="formData2" :model="formData2" :rules="rules" status-icon size="medium" label-width="100px">
              <el-col :span="24">
                <el-form-item label="" prop="category">
                  <el-input v-model="formData2.category" type="textarea" placeholder="分类设置" clearable :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item size="large">
                  <el-button type="primary" @click="submitForm2">提交</el-button>
                  <el-button @click="deleteSelectedVmItems">删除</el-button>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/api/request'
export default {
  data () {
    return {
      showAddForm: false,
      showAddForm2: false,
      formData: {},
      formData2: {},
      rules: {
        category: [{ required: true, message: '请输入分类', trigger: 'blur' }]
      },
      selectTc: [],
      selectVm: [],
      toggleInit: [],
      toggleInit2: [],
      pageSize: 2
    }
  },
  created () {
    this.toggleAddFormInit()
    this.toggleAddFormInit2()
  },
  methods: {
    selectTcItem (id) {
      if (this.selectTc.includes(id)) {
        // 如果数组中包含该 ID，则取消选择并从数组中移除
        this.selectTc = this.selectTc.filter(item => item !== id)
      } else {
        // 否则，选择该项目并将其添加到数组中
        this.selectTc.push(id)
      }
    },
    selectVmItem (id) {
      if (this.selectVm.includes(id)) {
        // 如果数组中包含该 ID，则取消选择并从数组中移除
        this.selectVm = this.selectVm.filter(item => item !== id)
      } else {
        // 否则，选择该项目并将其添加到数组中
        this.selectVm.push(id)
      }
      // alert(id)
    },
    toggleAddForm () {
      this.showAddForm = !this.showAddForm
    },
    toggleAddForm2 () {
      this.showAddForm2 = !this.showAddForm2
    },
    async toggleAddFormInit () {
      const token = localStorage.getItem('token')
      try {
        const resp = await request.get('/tcCategoryMedicine/tcMedicine', {
          headers: {
            accept: 'application/json',
            Authorization: 'Bearer ' + token
          }
        })
        const data = resp.data
        // alert(JSON.stringify(data.rows))
        // 默认选中所有
        this.pageSize = data.total
        this.toggleInit = data.data
        // this.toggleInit = data.data.map(item => ({ ...item, selected: true }))
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    deleteSelectedItems () {
      // alert(this.selectTc)
      if (this.selectTc.length === 0) {
        this.$message({
          message: '请选择要删除的选项',
          type: 'warning',
          center: true,
          offset: 80
        })
        return
      }
      this.$confirm('请确认信息是否正确！！！, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // const ids = this.selectTc.join(',')
        // alert(this.selectTc)
        const resp = await request.delete('/tcCategoryMedicine/delete/' + this.selectTc, {
          headers: {
            accept: 'application/json',
            Authorization: 'Bearer ' + localStorage.getItem('token')
          }
        })
        if (resp.data.flag === true) {
          this.$message({
            message: resp.data.message,
            type: 'success',
            center: true
          })
          await this.toggleAddFormInit()
        } else {
          this.$message({
            message: resp.data.message,
            type: 'error',
            center: true
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消',
          center: true
        })
      })
    },
    submitForm () {
      const token = localStorage.getItem('token')
      try {
        this.$confirm('请确认信息是否正确！！！, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs.elForm.validate((val) => {
            if (val) {
              request.post('/tcCategoryMedicine/add', this.formData, {
                headers: {
                  accept: 'application/json',
                  Authorization: 'Bearer ' + token
                }
              }).then(resp => {
                const data = resp.data
                // alert(JSON.stringify(data.rows))
                if (resp.data.flag === true) {
                  this.$message({
                    message: data.message,
                    type: 'success',
                    center: true
                  })
                  // await this.submitForm2()
                  this.toggleAddFormInit()
                } else {
                  this.$message({
                    message: data.message,
                    type: 'error',
                    center: true
                  })
                }
              }).catch(error => {
                this.handleAxiosError(error)
              })
            } else {
              this.$message({
                message: '请填写完整信息！！！',
                type: 'error',
                center: true
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
            center: true
          })
        })
        // 默认选中所有
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    async toggleAddFormInit2 () {
      const token = localStorage.getItem('token')
      try {
        const resp = await request.get('/tcCategoryMedicine/vmMedicine', {
          headers: {
            accept: 'application/json',
            Authorization: `Bearer ${token}`
          }
        })
        const data = resp.data
        // alert(JSON.stringify(data.rows))
        // 默认选中所有
        this.pageSize = data.total
        this.toggleInit2 = data.data
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    async submitForm2 () {
      const token = localStorage.getItem('token')
      if (this.formData2.category === '') {
        this.$message({
          message: '内容不能为空',
          type: 'error',
          center: true
        })
        return
      }
      try {
        this.$confirm('请确认信息是否正确！！！, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          request.post('/tcCategoryMedicine/addVm', this.formData2, {
            headers: {
              Authorization: `Bearer ${token}`
            }
          }).then(resp => {
            const data = resp.data
            // alert(JSON.stringify(data.rows))
            if (data.flag === true) {
              this.$message({
                message: data.message,
                type: 'success',
                center: true
              })
              // this.toggleAddForm2()
              this.toggleAddFormInit2()
            } else {
              this.$message({
                message: data.message,
                type: 'error',
                center: true
              })
            }
          }).catch(error => {
            this.handleAxiosError(error)
          })
        })
        // 默认选中所有
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    deleteSelectedVmItems () {
      // this.formData = {}
      // alert(this.selectVm)
      if (this.selectVm.length === 0) {
        this.$message({
          message: '请选择要删除的选项',
          type: 'warning',
          center: true,
          offset: 80
        })
        return
      }
      this.$confirm('请确认信息是否正确！！！, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const resp = await request.delete('/tcCategoryMedicine/deleteVm/' + this.selectVm, {
          headers: {
            accept: 'application/json',
            Authorization: 'Bearer ' + localStorage.getItem('token')
          }
        })
        if (resp.data.flag === true) {
          this.$message({
            message: resp.data.message,
            type: 'success',
            center: true
          })
          this.selectVm = []
          await this.toggleAddFormInit2()
        } else {
          this.$message({
            message: resp.data.message,
            type: 'error',
            center: true
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消',
          center: true
        })
      })
    },
    handleAxiosError (error) {
      // 检查是否是Axios的网络错误
      if (error.isAxiosError && error.response) {
        // 处理您的网络错误，例如显示用户友好的提示
        this.$message.error('网络请求失败，请稍后重试')
      } else {
        // 处理其他类型的错误
        this.$message.error('网络请求失败，发生错误，请稍后重试')
      }
    }
    // 其他可能的方法
  }
}
</script>

<style scoped>
.card-containers {
  display: flex;
  justify-content: space-between;
}

.containers {
  width: 100%; /* 设置为100% */
  /*border: 1px solid #ce6a6a;*/
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  white-space: nowrap;
}

.cards {
  border: 1px solid #ce6a6a;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.headers {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.content {
  margin-bottom: 16px;
}

.form-container {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 16px;
  background-color: #f5f5f5;
}

.list-item {
  font-size: 14px;
  text-align: left;
  margin-bottom: 8px;
}
</style>
